package org.feng.resource.impl;

import io.minio.*;
import org.feng.entity.Resource;
import org.feng.resource.ResourceUpload;
import org.feng.utils.UUIDUtil;

import java.io.InputStream;

/**
 * @author 冯帅
 * @des TODO
 * @date 2021/11/30 15:50
 * @email 15612509687@163.com
 */
public class Minio implements ResourceUpload {
    private Resource resource;
    private MinioClient minioClient;

    public Minio(Resource resource) {
        try {
            this.resource = resource;
            this.minioClient = MinioClient.builder()
                    .endpoint(resource.getEndpoint())
                    .credentials(resource.getKey(), resource.getSecret())
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void createBucket(String name) {
        try {
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteBucket(String name) {
        try {
            if (minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build())) {
                minioClient.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String putFile(InputStream stream, String fileName, Boolean override) {
        if (override) {
            try {
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(resource.getBucket())
                        .stream(stream, -1, -1)
                        .object(fileName)
                        .build());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUIDUtil.getUUID() + suffix;
            try {
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(resource.getBucket())
                        .stream(stream, -1, -1)
                        .object(fileName)
                        .build());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return getLink(fileName);
    }


    private String getLink(String fileName) {
        return this.resource.getEndpoint() + "/" + fileName;
    }
}
